package com.boss.salary.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boss.common.entity.PageDTO;
import com.boss.common.entity.WfActionDTO;
import com.boss.common.enums.ActionTypeEnum;
import com.boss.common.service.ICommonService;
import com.boss.common.util.DateUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.framework.exception.AppRuntimeException;
import com.boss.salary.constant.SystemDictConstant;
import com.boss.salary.dao.IAgencyVerifyDao;
import com.boss.salary.dao.IGenerateSalaryDataDao;
import com.boss.salary.dao.ISalaryPaymentTicketDao;
import com.boss.salary.entity.AgencyVerify;
import com.boss.salary.entity.SalaryPaymentRequisitionBack;
import com.boss.salary.entity.SalaryPaymentTicket;
import com.boss.salary.service.ISalaryPaymentTicketService;
import com.boss.salary.workflow.service.ISalaryWorkFlowService;
import com.boss.sys.ca.user.dto.UserDTO;
import com.boss.sys.utils.SysUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.String.valueOf;

@Service
public class SalaryPaymentTicketServiceImpl implements ISalaryPaymentTicketService {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(SalaryPaymentTicketServiceImpl.class);
    @Autowired
    private ISalaryPaymentTicketDao dao;
    @Autowired
    private ICommonService iCommonService;
    @Autowired
    private SalaryPaymentTicketServiceImpl salaryPaymentTicketService;
    @Autowired
    private IGenerateSalaryDataDao iGenerateSalaryDataDao;
    @Autowired
    private ISalaryWorkFlowService iSalaryWorkFlowService;
    @Autowired
    private IAgencyVerifyDao iAgencyVerifyDao;

    @Override
    public PageDTO<SalaryPaymentTicket> queryPaymentTicketPage(PaginationDTO paginationDTO,String mofDivCode,String agencyId,String flag, String agencyName, String payeeAcctNo, String payAppAmt, String payeeAcctName, String payeeAcctBankName) {
            List<SalaryPaymentTicket> paymentTicket = dao.queryPaymentTicketPage(paginationDTO,mofDivCode,agencyId,flag, agencyName, payeeAcctNo, payAppAmt, payeeAcctName, payeeAcctBankName);
            int total = dao.queryaymentTicket(mofDivCode,agencyId,flag,agencyName, payeeAcctNo, payAppAmt, payeeAcctName, payeeAcctBankName);
            PageDTO<SalaryPaymentTicket> pageDTO = new PageDTO<>();
            pageDTO.setRows(paymentTicket);
            pageDTO.setTotal(total);
            return pageDTO;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePaymentTicket(SalaryPaymentTicket salaryPaymentTicket) {
        salaryPaymentTicket.setUpdateTime(valueOf(DateUtils.getCurrentTimeStamp()));
        dao.updatePaymentTicket(salaryPaymentTicket);
    }
    //批量插入
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map insertPaymentTicket(List<SalaryPaymentTicket> salaryPaymentTickets,UserDTO userDTO) {
        List<String> agencyIds=new ArrayList<>();
        logger.info("==== 支付作废  传入："+salaryPaymentTickets.size()+"条作废数据===");
       for(SalaryPaymentTicket sp:salaryPaymentTickets) {
           if(agencyIds.contains(sp.getAgencyId())){
               continue;
           }
           agencyIds.add(sp.getAgencyId());
       }
       Map<String,Integer> payAgencycount=new HashMap<>();//执行返回各单位查询出来的数据
       Map<String,Integer> salaryAgencycount=new HashMap<>();//涉及到的单位现有生成申请数
        //通过传会来的 数据中的payId 去 sal_salary_payment_requisition_back 表中差数据
        List<SalaryPaymentTicket> PaymentBacks=dao.salaryPaymentBack(salaryPaymentTickets,userDTO.getProvince());//执行返回数据查询结果
        if(!CollectionUtils.isEmpty(PaymentBacks)) {
            for (SalaryPaymentTicket sp : PaymentBacks) {
                Integer count = payAgencycount.get(sp.getAgencyId()) == null ? 0 : payAgencycount.get(sp.getAgencyId());
                payAgencycount.put(sp.getAgencyId(), ++count);
            }
        }
        List<SalaryPaymentTicket> salaryPayment=dao.salaryPaymentBackByAgencyIds(agencyIds,userDTO.getProvince());//涉及到的单位现有生成申请数
        if(!CollectionUtils.isEmpty(salaryPayment)) {
            for (SalaryPaymentTicket sp : salaryPayment) {
                Integer count = salaryAgencycount.get(sp.getAgencyId()) == null ? 0 : salaryAgencycount.get(sp.getAgencyId());
                salaryAgencycount.put(sp.getAgencyId(), ++count);
            }
        }
        List<String> willWorkFlowAgencys=new ArrayList<>();
        for(String agencyid:agencyIds){
            Integer sc=salaryAgencycount.get(agencyid) == null ? 0 : salaryAgencycount.get(agencyid);;
            Integer pc=payAgencycount.get(agencyid)  == null ? 0 : payAgencycount.get(agencyid); ;
            logger.info("==== 单位 共："+sc+"笔申请===执行退回共："+pc+"笔");
            if(sc==pc&&pc+sc!=0){//查询的数据与为处理的数据一致说明所有申请都被退回，则将该单位归类为需走流程单位
                willWorkFlowAgencys.add(agencyid);
            }
        }
        logger.info("==== 支付作废  共："+agencyIds.size()+"家单位==="+agencyIds.toString());
        //0B045B74C8EF4DD4BCC3892A4E904F6B 工作流生成工资数据菜单id
        if(!CollectionUtils.isEmpty(willWorkFlowAgencys)) {//若需处理的单位数量不为空则走流程修改状态
            List<AgencyVerify> agencyVerify1s = iAgencyVerifyDao.getAgencyVerifyPayByAgencyIds(willWorkFlowAgencys);
            if(!CollectionUtils.isEmpty(agencyVerify1s)) {
                // 单位上报录入流程
                WfActionDTO<List<AgencyVerify>> wfActionDTO = new WfActionDTO();
                wfActionDTO.setMenuguid("69D0FD6E194F457993877285E3AB24FE");
                // 审核
                wfActionDTO.setActionType(ActionTypeEnum.WF_RECALL.getActionTypeCode());//撤销
                wfActionDTO.setBizDatas(agencyVerify1s);
                wfActionDTO.setBizKeyName("bizKey");
                // 财政确认后，执行工作流节点到下一节点
                logger.info("==== 支付作废工作流撤销生成 处理：" + agencyVerify1s.size() + "家单位  ===");
                iSalaryWorkFlowService.doSalaryFlowList(userDTO, wfActionDTO);
                for (AgencyVerify av : agencyVerify1s) {
                    av.setIsPayDataCreated(SystemDictConstant.IS_FALSE);
                    av.setIsBankDataCreated(SystemDictConstant.IS_FALSE);
                }
                iAgencyVerifyDao.batchUpdateFinancialVerifyStatus(agencyVerify1s);
            }
        }
         Map<String,Object>map= new HashMap<>();
         //查看 返回数数据多少条处理了多少条
         map.put("message","返回"+salaryPaymentTickets.size()+"条"+"处理"+PaymentBacks.size()+"条");

            iGenerateSalaryDataDao.deleteBatchPayBack(salaryPaymentTickets,userDTO.getProvince());//暂不处理原申请数据，存在部分退款问题，只做金额记录用
//       }
            return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String modifyIsPushAgain(List<Map<String,Object>> mapList,UserDTO userDTO,String tokenid) {
        List<Map<String,Object>> payList=new ArrayList<>();
        for(Map map:mapList){
            Map<String,Object> payMap=new HashMap<>();
            payMap.put("agency_id",map.get("agencyId"));
            payMap.put("bgt_id",map.get("bgtId"));
            payMap.put("payee_acct_name",map.get("payeeAcctName"));
            payMap.put("payee_acct_no",map.get("payeeAcctNo"));
            payMap.put("payee_acct_bank_name",map.get("payeeAcctBankName"));
            payMap.put("pay_app_amt",map.get("payAppAmt"));
            payMap.put("use_des",map.get("useName"));
            payMap.put("pay_app_amt_big", map.get("payAppAmt").toString().toUpperCase());
            payMap.put("set_mode_id", "7B13AE7CF40B4777BA4524E47A66BFF6");
            payMap.put("set_mode_code", "1");
            payMap.put("set_mode_name", "电子转账支付");
            payMap.put("internal_dep_id", "1000000008047469");
            payMap.put("internal_dep_code", "11");
            payMap.put("internal_dep_name", "办公室");

            payMap.put("fund_traobj_type_id", "FFCDE84E66DF46A2BDE16C222314C8BA");
            payMap.put("fund_traobj_type_code", "13");
            payMap.put("fund_traobj_type_name", "与同级财政");
            payList.add(payMap);
        }
       String  toPayment=salaryPaymentTicketService.toPayment(payList,userDTO,tokenid);
        dao.modifyIsPushAgain(mapList);
        return toPayment;
    }


    //@Override
    public String toPayment(List<Map<String, Object>> payListOneAgency, UserDTO userDto,String tokenid){
        JSONArray jsonArray =new JSONArray();
        Map<String,JSONObject> map= iCommonService.sentPayMent(payListOneAgency, tokenid);//每个单位单独走数据
        JSONObject result = map.get("result");
        String rscode = result.getString("rscode");
        List<String> agencyIds=new ArrayList<>();//反写需要走工作流的单位id
        for(Map map1:payListOneAgency){
            agencyIds.add(map1.get("agency_id").toString());
        }

        // 调用成功
        if ("200".equals(rscode)) {//将成功的数据单位id保存在集合中，后续处理
            jsonArray.addAll(result.getJSONArray("data"));
            savePayBackDatas(jsonArray,userDto,agencyIds);// 保存回单数据
        } else {
            logger.info(result.getString("result"));
            throw new AppRuntimeException(result.getString("result"));
//            requestMessage.append("F-"+result.getString("result")+"\n");
        }
        return  result.getString("result");
    }

    /**
     * 保存支付回单数据
     * @param jsonArray
     */
    private void savePayBackDatas(JSONArray jsonArray, UserDTO userDto, List<String> agencyIds) {
        List<SalaryPaymentRequisitionBack> salaryPaymentRequisitionBacks=new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            // 修改表状态，并添加模拟值
            String agencyId = jsonObject.getString("agency_id");
            SalaryPaymentRequisitionBack salaryPaymentRequisitionBack = new SalaryPaymentRequisitionBack();
            salaryPaymentRequisitionBack.setId(SysUtils.generateGuid());
            salaryPaymentRequisitionBack.setCreateTime(valueOf(DateUtils.getCurrentTimeStamp()));
            salaryPaymentRequisitionBack.setUpdateTime(valueOf(DateUtils.getCurrentTimeStamp()));
            salaryPaymentRequisitionBack.setAgencyId(agencyId);
            salaryPaymentRequisitionBack.setAgencyName(jsonObject.getString("agency_name"));
            salaryPaymentRequisitionBack.setPayId(jsonObject.getString("id"));
            salaryPaymentRequisitionBack.setPayAppNo(jsonObject.getString("pay_app_no"));
            salaryPaymentRequisitionBack.setBgtId(jsonObject.getString("bgt_id"));
            salaryPaymentRequisitionBack.setPayAppAmt(jsonObject.getString("pay_app_amt"));
            salaryPaymentRequisitionBack.setFundType(jsonObject.getString("fund_type"));
            salaryPaymentRequisitionBack.setPayeeAcctName(jsonObject.getString("payee_acct_name"));
            salaryPaymentRequisitionBack.setPayeeAcctNo(jsonObject.getString("payee_acct_no"));
            salaryPaymentRequisitionBack.setPayeeAcctBankName(jsonObject.getString("payee_acct_bank_name"));
            salaryPaymentRequisitionBack.setPayType(jsonObject.getString("pay_type"));
            salaryPaymentRequisitionBack.setProCat(jsonObject.getString("pro_cat"));
            salaryPaymentRequisitionBack.setGovBgtEco(jsonObject.getString("gov_bgt_eco"));
            salaryPaymentRequisitionBack.setDepBgtEco(jsonObject.getString("dep_bgt_eco"));
            salaryPaymentRequisitionBack.setPro(jsonObject.getString("pro"));
            salaryPaymentRequisitionBack.setUseName(jsonObject.getString("use_"));
            salaryPaymentRequisitionBack.setExpFunc(jsonObject.getString("exp_func"));
            salaryPaymentRequisitionBack.setMofDivCode(userDto.getProvince());
            salaryPaymentRequisitionBack.setIsDeleted(SystemDictConstant.IS_FALSE);
            salaryPaymentRequisitionBacks.add(salaryPaymentRequisitionBack);
        }
       iGenerateSalaryDataDao.batchInsertPayBackData(salaryPaymentRequisitionBacks);
    }


}
